package com.bidevalution.controller.task;

import com.bidevalution.business.service.*;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSignLocation;
import com.bidevalution.dao.entity.BeSignlocationDistance;
import com.bidevalution.support.context.TencentApiConfig;
import com.chatroom.api.constant.MemberDisplay;
import com.chatroom.api.constant.MemberType;
import com.chatroom.api.dto.ChatGroupInfoDTO;
import com.chatroom.api.dto.ChatUserInfoDTO;
import com.chatroom.api.service.ChatGroupInfoApiService;
import com.chatroom.api.service.ChatGroupMemberApiService;
import com.chatroom.api.service.ChatUserForbidApiService;
import com.chatroom.api.service.ChatUserInfoApiService;
import com.qtp.core.util.DateUtil;
import com.tls.tls_sigature.tls_sigature;
import com.tls.tls_sigature.tls_sigature.GenTLSSignatureResult;
import lombok.extern.log4j.Log4j2;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//@Component
public class ChatroomTask {
	@Autowired
	private BeSectionInfoService beSectionInfoService;
	@Value("${SystemIdentify}")
	private String appKey;
	@Autowired
	private ChatGroupInfoApiService chatGroupInfoApiService;
	@Autowired
	private ChatGroupMemberApiService chatGroupMemberApiService;
	@Autowired
	private ChatUserForbidApiService chatUserForbidApiService;
	@Autowired
	private BeSectionParticipantService beSectionParticipantService;
	@Autowired
	private ChatUserInfoApiService chatUserInfoApiService;
	@Autowired
	private BeSignLocationService beSignLocationService;
	@Autowired
	private BeSignLocationDistanceService beSignLocationDistanceService;
	@Autowired
	private BeNoticeDataService beNoticeDataService;
	private Logger log = Logger.getLogger(getClass());
	/**
	 * 1分钟执行一次
	 * 
	 * @throws Exception
	 */
	//@Scheduled(cron = "0 */1 *  * * * ")
	public void initData() {
		String groupId = "";
		String chatUserId = "";
		ChatGroupInfoDTO chatGroupInfoDTO;
		for (BeSectionInfo beSectionInfo : beSectionInfoService.getChatSectionList()) {
			chatGroupInfoDTO = chatGroupInfoApiService.getByBusinessGroupId(appKey,
					beSectionInfo.getSeqId());
			if (chatGroupInfoDTO == null) {
				groupId = chatGroupInfoApiService.addGroup(appKey, "开标交流群", beSectionInfo.getSeqId(), "group.png", 0);
			} else {
				groupId = chatGroupInfoDTO.getGroupId();
			}
			
			try {
				// 投标人同步数据到互动聊天
				for (Map<String, String> dataMap : beSectionParticipantService
						.queryParticipantList(beSectionInfo.getSeqId())) {

					if (dataMap.get("orgEnterId") != null) {
						GenTLSSignatureResult result = tls_sigature.GenTLSSignatureEx(
								TencentApiConfig.tencentApiSdkAppid, appKey + "_chat_" + dataMap.get("orgEnterId"),
								TencentApiConfig.tencentApiPrivatekey);
						ChatUserInfoDTO chatUserInfoDTO = chatUserInfoApiService.getChatUserInfo(appKey,
								dataMap.get("orgEnterId").toString());
						if (chatUserInfoDTO != null) {
							chatUserInfoApiService.updateUser(appKey, dataMap.get("orgEnterId").toString(),
									dataMap.get("orgName"), "tbr.png", result.urlSig);
							chatUserId = chatUserInfoDTO.getUserId();
						} else {
							chatUserId = chatUserInfoApiService.addUser(appKey, dataMap.get("orgEnterId").toString(),
									dataMap.get("orgName"), "tbr.png", result.urlSig);
						}
						chatGroupMemberApiService.addMember(appKey, groupId, chatUserId, MemberType.common,
								MemberDisplay.Invisible);
					}
				}
			} catch (Exception e) {
                log.error(e.getMessage(), e);
			}

		}
	}

	/**
	 * 解除质疑
	 */
	//@Scheduled(cron = "0 */1 *  * * * ")
	public void removeQuestion() {
		// 获取当天到期的质疑
		for (ChatGroupInfoDTO chatGroupInfo : chatGroupInfoApiService
				.selectListByForbidTimeout(DateUtil.getAfterDay(new Date(), -1), new Date(), -2)) {
			// 如果用户禁言表中未存在没有点击结束质疑的用户
			if (chatUserForbidApiService.selectCount(chatGroupInfo.getBusinessId(), -2) == 0) {
				// 开启群聊天
				chatGroupInfoApiService.addGroup(chatGroupInfo.getAppKey(), chatGroupInfo.getGroupName(),
						chatGroupInfo.getBusinessId(), chatGroupInfo.getAvatarUrl(), -1);
				beNoticeDataService.addC14(chatGroupInfo.getBusinessId(), new Date());
			}
		}
		for (ChatGroupInfoDTO chatGroupInfo : chatGroupInfoApiService
				.selectListByForbidTimeout(DateUtil.getAfterDay(new Date(), -1), new Date(), -1)) {
			// 关闭个人聊
			chatUserForbidApiService.deleteByBusinessId(chatGroupInfo.getBusinessId());
		}
		for (ChatGroupInfoDTO chatGroupInfo : chatGroupInfoApiService
				.selectListByForbidTimeout(DateUtil.getAfterDay(new Date(), -1), new Date(), -2)) {
			if (chatGroupInfo.getForbidTimeout() != -2) {
				chatUserForbidApiService.deleteByForbidTimeout(chatGroupInfo.getBusinessId(), -2);
			}
		}
	}

	/**
	 * 地图距离计算3分钟执行一次
	 */
	@Scheduled(cron = "0 */3 *  * * * ")
	public void computeGapDistance() {
		BeSignlocationDistance beSignlocationDistance;
		double distance;
		List<BeSignLocation> beSignLocations = beSignLocationService
				.selectListByCreateTime(DateUtil.getAfterDay(new Date(), -1));
		for (BeSignLocation beSignLocation : beSignLocations) {
			beSignLocationDistanceService.deleteByComputeLocationId(beSignLocation.getId());
			for (BeSignLocation beSignLocation2 : beSignLocations) {
				if (!beSignLocation.getId().equals(beSignLocation2.getId())
						&& beSignLocation.getSectionId().equals(beSignLocation2.getSectionId())) {
					beSignlocationDistance = new BeSignlocationDistance();
					beSignlocationDistance.setId(UUID.randomUUID().toString());
					beSignlocationDistance.setCreateTime(new Date());
					distance = distance(Double.valueOf(beSignLocation.getLongitude()),
							Double.valueOf(beSignLocation.getLatitude()),
							Double.valueOf(beSignLocation2.getLongitude()),
							Double.valueOf(beSignLocation2.getLatitude()));
					beSignlocationDistance.setDistance(Double.valueOf(distance).intValue());
					beSignlocationDistance.setLatitude(beSignLocation2.getLatitude());
					beSignlocationDistance.setLongitude(beSignLocation2.getLongitude());
					beSignlocationDistance.setSignLocationId(beSignLocation2.getId());
					beSignlocationDistance.setComputeLocationId(beSignLocation.getId());
					beSignLocationDistanceService.insert(beSignlocationDistance);
				}
			}
		}

	}

	/**
	 * 计算地球上任意两点(经纬度)距离
	 * 
	 * @param long1 第一点经度
	 * @param lat1  第一点纬度
	 * @param long2 第二点经度
	 * @param lat2  第二点纬度
	 * @return 返回距离 单位：米
	 */
	public static double distance(double long1, double lat1, double long2, double lat2) {
		double a, b, R;
		R = 6378137; // 地球半径
		lat1 = lat1 * Math.PI / 180.0;
		lat2 = lat2 * Math.PI / 180.0;
		a = lat1 - lat2;
		b = (long1 - long2) * Math.PI / 180.0;
		double d;
		double sa2, sb2;
		sa2 = Math.sin(a / 2.0);
		sb2 = Math.sin(b / 2.0);
		d = 2 * R * Math.asin(Math.sqrt(sa2 * sa2 + Math.cos(lat1) * Math.cos(lat2) * sb2 * sb2));
		return d;
	}

	public static void main(String[] args) {
		System.out.println(distance(120.72264099121094, 28.010955810546875, 120.72264099121094, 28.010955810546875));
	}
}
